global class LeadEmailProcessor implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {
 
    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
 
    Lead lead = new Lead();
    if(email.fromname.indexOf(' ') > 0) {
    lead.FirstName = email.fromname.substring(0,email.fromname.indexOf(' '));
    lead.LastName = email.fromname.substring(email.fromname.indexOf(' '));    
    }else { 
    //lead.FirstName = email.fromname.substring(0,email.fromname.indexOf('@'));   
    lead.LastName = email.fromname; //.substring(email.fromname.indexOf(' '));
    }
    lead.Email = envelope.fromAddress;
    lead.Description = 'Subject = ' + email.subject + '\n Body = ' + email.plainTextBody;
    lead.Original_Email__c = envelope.toAddress;
    lead.LeadSource = 'Inbound Email';
    //get company from domain
    string company = envelope.fromAddress.substring(envelope.fromAddress.indexOf('@'));
    lead.Company = company.substring(1);
    
    
    //try
    insert lead;
 
    System.debug('====> Created contact '+lead.Id);
    
    if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
      for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
        Attachment attachment = new Attachment();
        // attach to the newly created contact record
        attachment.ParentId = lead.Id;
        attachment.Name = email.binaryAttachments[i].filename;
        attachment.Body = email.binaryAttachments[i].body;
        insert attachment;
      }

    }
      
    return result;

  }
  
  
static testMethod void testMe() {
 
  // create a new email and envelope object
  Messaging.InboundEmail email = new Messaging.InboundEmail() ;
  Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
 
  // setup the data for the email
  email.subject = 'Test Job Applicant';
  email.fromname = 'FirstName LastName';
  env.fromAddress = 'someaddress@email.com';
  
  // add an attachment
  Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
  attachment.body = blob.valueOf('my attachment text');
  attachment.fileName = 'textfile.txt';
  attachment.mimeTypeSubType = 'text/plain';
  
  email.binaryAttachments =
    new Messaging.inboundEmail.BinaryAttachment[] { attachment };
 
 
 
  // call the email service class and test it with the data in the testMethod
  LeadEmailProcessor emailProcess = new LeadEmailProcessor();
  emailProcess.handleInboundEmail(email, env);
 
  // query for the contact the email service created
  Lead lead = [select id, firstName, lastName, email from Lead
    where firstName = 'FirstName' and lastName = 'LastName'];
 
  System.assertEquals(lead.firstName,'FirstName');
  System.assertEquals(lead.lastName,'LastName');
  System.assertEquals(lead.email,'someaddress@email.com');
 

 
}


}